import 'dart:async';
import 'dart:convert';

import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/map_location_controller.dart';
import 'package:dmz/business/home/controller/map_saver_controller.dart';
import 'package:dmz/business/home/model/moto_config.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/home/page/main_page.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/tools/blue/blue_business.dart';
import 'package:dmz/tools/blue/blue_config.dart';
import 'package:dmz/tools/blue/blue_manger.dart';
import 'package:dmz/tools/blue/blue_tools.dart';
import 'package:dmz/user/user_defurl.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';

import '../../mine/controller/garage_main_controller.dart';
import '../../mine/model/share_model.dart';
import '../model/moto_version.dart';
import '../widgets/DefaultDialog.dart';
import '../widgets/ForceDialog.dart';

class HomePageController extends BaseController {
  List<MotoModel> motoList = [];
  PageController pageController = PageController();
  int pageIndex = 0;
  MotoVersion motoVersion = MotoVersion();
  RxBool open = false.obs;
  bool showBottom = false;
  bool defaultBottom = false;
  bool forceBottom = false;
  bool dontGetVison = false;

  /// 0 网点服务 1 电子围栏 2 钥匙分享 3 骑行统计 4轨迹列表 5 车辆位置
  List<int> bottomkeys = [0, 1, 2, 3, 4, 5];

  RxList<ShareModel> shareList = <ShareModel>[].obs;
  bool haveNewShare = false;
  Timer? timer;

  // final sleelctMoto = Rx<MotoModel>(MotoModel());

  @override
  void onInit() {
    super.onInit();
    debugPrint('数据加载');
    getMotolist();
    startTimer();
  }

  @override
  void loadNet() {}

  @override
  void onHidden() {}

  ///获取车辆列表
  void getMotolist() {
    motoList.clear();
    motoList.add(MotoModel());
    RequestClient().post<List<MotoModel>>(APIS.motoList,
        queryParameters: {}).then((value) {
      if (value != null) {
        motoList.insertAll(0, value);
      }
      update();
      if (pageIndex != 0) {
        pageIndex = 0;
        Get.find<HomePageController>().pageController.jumpToPage(pageIndex);
      } else {
        debugPrint('车辆列表 ${value} ${motoList.length}');
        // getMotoData();
        if (value?.first.sn_code != null) {
          vehicleBluetoothConnection(value!.first.sn_code!, value.first.name!,
              value.first.mac ?? '90:CD:1F:16:1E:A8'); //mac地址
          if (value.first.socket_type == 1) {
            debugPrint('车辆列表  ${value.first.id}');
            get4GDeviceStatus(value.first.id ?? 0);
          }
        }
      }
    });
  }

  ///获取车辆状态
  get4GDeviceStatus(int id) {
    RequestClient()
        .post<Map>(APIS.deviceStatus, data: {'ebike_id': id}).then((value) {
      if (value != null) {
        var data = motoList[pageIndex];
        data.lock_status = value['lock_status'];
        data.power_status = value['power_status'];
        data.online_status = value['online_status'];
        if (data.online_status == 0 && data.isOpen) {
          data.isOpen = false;
          update(['Moto$pageIndex']);
        }

        if (data.online_status == 1) getMotoBattery(id);
      }
    });
  }

  ///车辆刷新
  didVehicleRefresh(bool refresh) {
    if (refresh && motoList[pageIndex].id != null) {
      debugPrint('车辆刷新');
      get4GDeviceStatus(motoList[pageIndex].id ?? 0);
    }
  }

  ///获取电池电量
  getMotoBattery(int id) {
    RequestClient().post<Map>(APIS.getMotoMsg,
        data: {'ebike_id': 3, 'cmd': 'Battery'}).then((value) {
      if (value != null) {
        motoList[pageIndex].power = value['soc'];
        update(['Moto$pageIndex']);
      }
    });
  }

  ///切换车辆
  void changeMoto(int index) {
    pageIndex = index;
    var model = motoList[pageIndex];
    debugPrint('切换车辆 -- ${EMIBlueMangered().contnetNames}');

    if (model.sn_code != null &&
        !EMIBlueMangered().contnetNames.contains(model.name!) &&
        !model.contentBlue) {
      vehicleBluetoothConnection(
          model.sn_code!, model.name!, model.mac ?? '90:CD:1F:16:1E:A8');
    }
  }

  ///添加新的车辆
  void getNewMoto(String snCode) {
    RequestClient().post<MotoModel>(APIS.findMoto,
        data: {'sn_code': snCode}).then((value) {
      if (value != null) {
        value.contentBlue = true;
        value.sn_code = snCode;
        motoList.insert(0, value);
        pageIndex = 0;
        update();
        pageController.jumpTo(0);
        debugPrint('添加新车辆列表 ${value} ${motoList.length}');
        getMotoConfigData();
        getBLEData();
        Future.delayed(const Duration(seconds: 5), () {
          if (!motoList[pageIndex].contentBlue) getMotoData();
        });
      }
    });
  }

  /// 无车辆 页面按钮点击
  void clickActionWithOnMoto(HomeMotoAction type, {int? other}) {
    if (type == HomeMotoAction.none) {
      EMILoding.hitLoding('请绑定车辆后再进行操作'.tr);
    } else {
      Get.toNamed(RouteGet.addBicke);
    }
  }

  /// 已绑定车辆 页面按钮点击
  void clickActionWithMoto(HomeMotoAction type, {int? other}) {
    switch (type) {
      case HomeMotoAction.add:
        Get.toNamed(RouteGet.addBicke);
        break;
      case HomeMotoAction.netxt:
        int indexed = pageIndex + 1;
        if (indexed >= motoList.length) return;
        pageController.animateToPage(indexed,
            duration: const Duration(milliseconds: 300), curve: Curves.ease);
        pageIndex = indexed;
        break;
      case HomeMotoAction.previous:
        int indexed = pageIndex - 1;
        if (indexed < 0) return;
        pageController.animateToPage(indexed,
            duration: const Duration(milliseconds: 300), curve: Curves.ease);
        pageIndex = indexed;
        break;
      case HomeMotoAction.open:
        debugPrint('开始启动');
        vehicleStarts();
        break;
      case HomeMotoAction.seat:
        openTrunk();
        break;
      case HomeMotoAction.contnent:
        changeMoto(pageIndex);
        break;
      case HomeMotoAction.bottom:
        turnOtherPage(other!);
        break;
      case HomeMotoAction.set:
        Get.toNamed(RouteGet.setMoto);
        break;
      case HomeMotoAction.foundDevice:
        foundMoto();
        break;
      case HomeMotoAction.other:
        didRestart();
        break;
      default:
    }
  }

  ///中控重启
  didRestart() {
    if (kDebugMode) {
      EMIBlueMangered().sendData(motoList[pageIndex].sn_code ?? '',
          action: EMIBlueACT.restart);
    }
  }

  ///底部功能栏点击
  turnOtherPage(int other) {
    /// 0 网点服务 1 电子围栏 2 钥匙分享 3 骑行导航 4轨迹列表 5 车辆位置
    switch (other) {
      case 0:
        Get.toNamed(RouteGet.servePoitn);
        break;
      case 1:
        Get.toNamed(RouteGet.map, arguments: true);
        break;
      case 2:
        Get.toNamed(RouteGet.shareKey, arguments: motoList[pageIndex]);
        break;
      case 3:
        Get.toNamed(RouteGet.motoNavigation);
        break;
      case 4:
        Get.toNamed(RouteGet.runMessage);
        break;
      case 5:
        Get.toNamed(RouteGet.motoLocation);
        break;
      default:
    }
  }

  ///车辆连接蓝牙
  void vehicleBluetoothConnection(String snCode, String name, String mac) {
    debugPrint('蓝牙 初始化连接 -----  $snCode  ');
    EMIBlueMangered().contentDeviceWithSN(snCode, mac, (success) {
      if (success) {
        EMIBUserManger().snCode = snCode;
        debugPrint('连接成功 $snCode $snCode');
        motoList[pageIndex].contentBlue = true;
        // getBLEData();
      } else {
        debugPrint('连接断开 $snCode  ');
        motoList[pageIndex].contentBlue = false;
      }
      update(['Moto$pageIndex']);
    });
    //获取配置信息
    getMotoConfigData();
    //通过蓝牙获取运行信息
    Future.delayed(const Duration(seconds: 10), () {
      if (!motoList[pageIndex].contentBlue) getMotoData();
    });
  }

  ///获取车辆配置信息
  void getMotoConfigData() {
    RequestClient().post<Map>(APIS.motoConfig,
        data: {'id': motoList[pageIndex].device_type_id}).then((value) {
      if (value != null) {
        motoList[pageIndex].config =
            MotoConfig.turnConfig(jsonDecode(value['func_config']));
        if (!dontGetVison) getVersion(motoList[pageIndex].sn_code);
        getBottomDatas();
      }
    });
  }

  getBottomDatas() {
    List<int> result = [];
    var config = motoList[pageIndex].config;
    for (var element in bottomkeys) {
      switch (element) {
        case 0:
          result.add(0);
          break;
        case 1:
          if (config?.electric_fence == 1) result.add(1);
          break;
        case 2:
          if (config?.key_sharing == 1) result.add(2);
          break;
        case 3:
          if (config?.ride_statistics == 1) result.add(3);
          break;
        case 4:
          if (config?.track_list == 1) result.add(4);
          break;
        case 5:
          if (config?.bike_location == 1) result.add(5);
          break;
        default:
      }
    }

    motoList[pageIndex].configResult = result;
    motoList[pageIndex].configStr = [
      '网点服务',
      '电子围栏',
      '钥匙分享',
      '骑行导航',
      '轨迹列表',
      '车辆位置'
    ];
    debugPrint(
        '车辆配置信息 --- ${motoList[pageIndex].configResult} ${motoList[pageIndex].configStr}');
    update(['Moto$pageIndex']);
  }

  ///车辆启动
  void vehicleStarts() {
    //!motoList[pageIndex].contentBlue
    if (!motoList[pageIndex].contentBlue) {
      RequestClient().post(APIS.sendCmd, data: {
        'ebike_id': motoList[pageIndex].id,
        'cmd': motoList[pageIndex].isOpen ? 1 : 0
      }).then((value) {
        motoList[pageIndex].isOpen = !motoList[pageIndex].isOpen;
        update(['Moto$pageIndex']);
        // debugPrint('车辆启动 --- $value');
      });
      return;
    }
    EMIBlueBusiness.deviceOperate(
        EMIBUserManger().snCode!,
        !motoList[pageIndex].isOpen
            ? EMIBlueACT.setDeviceOpen
            : EMIBlueACT.setDeviceClose, callback: (String content) {
      motoList[pageIndex].isOpen = !motoList[pageIndex].isOpen;
      update(['Moto$pageIndex']);
    });
  }

  ///座椅打开
  void openTrunk() {
    if (!motoList[pageIndex].contentBlue) {
      RequestClient().post(APIS.sendCmd,
          data: {'ebike_id': motoList[pageIndex].id, 'cmd': 4}).then((value) {
        motoList[pageIndex].sateOpen = !motoList[pageIndex].sateOpen;
        update(['Moto$pageIndex']);
        // debugPrint('车辆启动 --- $value');
      });
      return;
    }
    EMIBlueBusiness.deviceOperate(
        EMIBUserManger().snCode!, EMIBlueACT.openTrunk,
        callback: (String content) {
      motoList[pageIndex].sateOpen = !motoList[pageIndex].sateOpen;
      update(['Moto$pageIndex']);
    });
  }

  void foundMoto({bool automaticClose = false}) {
    if (!motoList[pageIndex].funded && !automaticClose) {
      ///8秒后自动关闭车辆位置找寻
      Future.delayed(const Duration(seconds: 8), () {
        foundMoto(automaticClose: true);
      });
    }
    if (!motoList[pageIndex].contentBlue) {
      RequestClient().post(APIS.sendCmd, data: {
        'ebike_id': motoList[pageIndex].id,
        'play_voice': 8
      }).then((value) {
        motoList[pageIndex].sateOpen = !motoList[pageIndex].sateOpen;
        update(['Moto$pageIndex']);
        // debugPrint('车辆启动 --- $value');
      });
      return;
    }
    EMIBlueBusiness.deviceOperate(
        EMIBUserManger().snCode!,
        motoList[pageIndex].funded
            ? EMIBlueACT.endFoundDevice
            : EMIBlueACT.stareFoundDevice, callback: (String content) {
      motoList[pageIndex].funded = !motoList[pageIndex].funded;
      update(['Moto$pageIndex']);
    });
  }

  ///获取车辆运行信息
  void getBLEData() {
    var model = motoList[pageIndex];

    if (model.battery_type == 1) {
      //获取电量
      snedBLEData(EMIBlueACT.queryElectrictStatus);
    }

    if (model.socket_type == 1) {
      //获取4G  GPS强度
      snedBLEData(EMIBlueACT.query4GAndGPS);
    }
  }

  ///网络获取车辆运行信息
  void getMotoData() {
    if (motoList[pageIndex].id == null) return;
    RequestClient().post<Map>(APIS.operationInfo,
        data: {'ebike_id': motoList[pageIndex].id}).then((value) {
      debugPrint('网络获取车辆运行信息 --- $value');
      motoList[pageIndex].have4G = value?['net'] as bool;
      motoList[pageIndex].haveGPS = value?['gps'] as bool;
      update(['Moto$pageIndex']);
    });
  }

  ///发送蓝牙指令
  void snedBLEData(EMIBlueACT type) {
    EMIBlueBusiness.deviceOperate(EMIBUserManger().snCode!, type,
        callback: (String content) {
      if (type == EMIBlueACT.queryElectrictStatus) {
        var dataList = EMIBlueTool.hexStringToIntList(content);
        var resulted = dataList.sublist(2, 4).reversed.toList();
        int result = resulted.fold(0, (prev, element) => (prev << 8) + element);
        debugPrint('蓝牙 当前电量 --$content $result $resulted $dataList');
        motoList[pageIndex].power = (result * 0.1).toInt();
      }
      if (type == EMIBlueACT.query4GAndGPS) {
        motoList[pageIndex].haveGPS =
            motoList[pageIndex].have4G = int.parse(content) > 0;
      }
      update(['Moto$pageIndex']);
    });
  }

  void getVersion(String? sn_code) {
    RequestClient().post<MotoVersion>(APIS.checkVersion,
        data: {'sn_code': sn_code}).then((value) {
      if (value != null) {
        motoVersion = value;
        defaultBottom = false;
        showBottom = false;
        forceBottom = false;
        update();
        debugPrint('${motoVersion.upgrade_type}');
        if (motoVersion.upgrade_type == 1) {
          //自主升级
          showDefaultDialog();
        } else if (motoVersion.upgrade_type == 2) {
          //强制升级
          showForceDialog();
        }
      }
      debugPrint('检测新版本');
    });
  }

  showDefaultDialog() {
    if (!defaultBottom) {
      defaultBottom = true;
      showBottom = true;
      EMILoding.showBottomWindow(
        DefaultDialog(
          model: motoVersion,
        ),
      );
    }
  }

  showForceDialog() {
    if (!forceBottom) {
      showBottom = true;
      forceBottom = true;
      EMILoding.showBottomWindow(
        ForceDialog(
          model: motoVersion,
        ),
      );
    }
  }

  ///开始计时
  void startTimer() {
    timer?.cancel();
    // 每隔一秒更新倒计时数字
    timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      getAcceptShareList();
    });
  }

  void getAcceptShareList() {
    // RequestClient().post<SharePageData>(APIS.shareDeviceList,
    //     data: {'type': 1}).then((value) {
    //   if (value != null && value.list != null) {
    //     var datas = shareList.value;
    //     datas.addAll(value.list as Iterable<ShareModel>);
    //     shareList.value = datas;
    //     var dataed =
    //         shareList.value.where((element) => element.status == 1).toList();
    //     if (haveNewShare != dataed.isNotEmpty) {
    //       haveNewShare = dataed.isNotEmpty;
    //       update();
    //     }
    //   }
    // });
  }

  turnShareList() {
    Get.put(GarageController());
    Get.find<GarageController>().selectIndex.value = 2;
    Get.find<GarageController>().pageController =
        PageController(initialPage: 2);
    Get.find<GarageController>().getAcceptShareList();
    Get.toNamed(RouteGet.garagePage)?.then((value) {
      getMotolist();
    });
  }

  @override
  void onClose() {
    timer?.cancel();
    super.onClose();
  }

  ///页面底部收缩
  void bottomAction() {
    MainController mainct = Get.find();
    mainct.bottomAction();
  }
}

class HomeBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => HomePageController());
    Get.lazyPut(() => MotoLocationController());
    Get.lazyPut(() => MapServePointController());
    Get.lazyPut(() => GarageController());
  }
}

enum HomeMotoAction {
  netxt, //下一个
  previous, //上一个
  open, //车辆开关
  set, //设置
  none, //无
  add, //添加车辆
  seat, //车座操作
  contnent, //切换车辆
  bottom, //底部按钮
  foundDevice,
  other, //切换车辆
}
